#!/bin/sh
#name:@invisible
#desc:Add agent to the network
#package:oddiscovery
#type:local

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

CNF_PATH=/etc/opendomo/discovery/services
NETPASS=`cat /etc/opendomo/discovery/password`
EXECREMOTE=/usr/local/opendomo/discovery/execRemoteScript.sh

if test -z "$2"
then
	# -------------------------------------------------------------------------
	# Input Form
	# -------------------------------------------------------------------------
	echo "form:`basename $0`"
	if test -z "$1"; then
      # Eliminar/Sustituir: la ip no debe introducirse manualmente
		echo "	ip	ip	text	$1"	
	else
		echo "	ip	ip	hidden	$1"
	fi
	
	echo "	name	Agent name	text	Agent_$1"
	echo "	pass	Agent password	text	opendomo"
else	
	# -------------------------------------------------------------------------
	# Add agent 
	# -------------------------------------------------------------------------
	IP="$1"
	ANAME="$2"
	APASS="$3"
	ODP=/usr/local/opendomo/discovery

	if $ODP/acceptSSHFingerprint.sh $IP > /dev/null 
	then
		echo "# Host [$IP] added to the network"
	else
		exit 0
	fi

	R=`$EXECREMOTE $IP "usermm $APASS set admin $NETPASS"`
	if test -z "$R"
	then
		echo "# Network password established"
		$EXECREMOTE $IP "echo $ANAME > /etc/opendomo/uid"
		$EXECREMOTE $IP "echo $NETPASS > /etc/opendomo/discovery/password"
	else
		echo "#ERR Password incorrect"
		if echo $IP | grep '^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$' > /dev/null
		then
			sed -i /$IP/d /home/admin/.ssh/known_hosts 2>/dev/null
		fi
	fi


fi
echo
